package com.ddframework.orm.datasource;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;

import com.ddframework.orm.tools.Constant;
import com.ddframework.orm.tools.XMLFactory;

/**
 * DB's connection control class
 * 
 * @author Wang Ding
 * 
 */
public class DBControl {

	private static Map<String, String> DBMAP = null;
	private Connection conn = null;
	static {
		load();
	}

	private static void load() {
		if (null == DBMAP) {
			XMLFactory.getXMLInfo(XMLFactory.class.getResource(
					"/ddorm.datasource.xml").getFile());
			DBMAP = Constant.DBMAP;

		}

	}

	public DBControl() {
		if (null == DBMAP) {
			load();
		} else {

			getSimpleConn();
		}
	}

	public Connection getSimpleConn() {
		try {
			Class.forName(DBMAP.get("driver"));
			conn = DriverManager.getConnection(DBMAP.get("url"),DBMAP.get("username"),DBMAP.get("password"));

		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	public void setData(String sql){
		Statement stmt;
		try {
			stmt = conn.createStatement();
			stmt.executeUpdate(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		
	}
	
	public void close(){
		try{
			if(conn!=null||!conn.isClosed()){
				conn.close();
			}
			
		}catch(SQLException ex){
			ex.printStackTrace();
		}
		
	}
	
	

}
